package com.xiaoma.common.observer.resume

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.xiaoma.common.extend.runOnMainThread
import com.xiaoma.common.observer.Observer
import java.util.concurrent.ConcurrentHashMap

/**
 * author: liangjingbo
 * date: 2022/7/30
 * describe:
 */
class ResumeObserver<T>(
    private val owner: LifecycleOwner,
    val observer: Observer<T>,
    private val mWrappers: ConcurrentHashMap<Observer<T>, ResumeObserver<T>>
) : LifecycleEventObserver {

    companion object {
        const val TAG = "ResumeObserverWrapperTag"
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        val currentState = owner.lifecycle.currentState
        if (currentState == Lifecycle.State.DESTROYED) {
            mWrappers.remove(observer)
            owner.lifecycle.removeObserver(this)
            return
        }
    }

    fun setData(value: T) {
        val currentState = owner.lifecycle.currentState
        if (currentState == Lifecycle.State.RESUMED) {
            runOnMainThread {
                observer.onChange(value)
            }
        }
    }
}